package indy.test.indy;

import java.lang.invoke.CallSite;
import java.lang.invoke.ConstantCallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodHandles.Lookup;
import java.lang.invoke.MethodType;
import java.lang.invoke.SwitchPoint;

public class SwitchPointTestTemplate {
    private static final SwitchPoint SWITCH_POINT = new SwitchPoint();
    
    private static void test() {
        check(test1());
        check(test2());
        check(test1());
    }
    
    private static void check(boolean test) {
        if (test) {
            System.out.println("pass");
            System.exit(0);
        }
    }

    public static void main(String[] args) throws Throwable {
        if (SWITCH_POINT.hasBeenInvalidated()) {
            throw new AssertionError();
        }
        
        for(int i=0; i<100_000; i++) {
              test();
              
              if (i == 50_000) {
                  SwitchPoint.invalidateAll(new SwitchPoint[]{SWITCH_POINT});
              }
        }
        System.err.println("failure !");
        throw new Throwable("failure !");
    }

    private static boolean test1() {
        return false;
    }

    private static boolean test2() {
        return false;
    }
    
    public static CallSite bsm(Lookup lookup, String name, MethodType type) throws NoSuchMethodException, IllegalAccessException {
        MethodHandle mh = lookup.findStatic(lookup.lookupClass(), name, type);
        
        if (name.equals("test2")) {
            mh = SWITCH_POINT.guardWithTest(mh, MethodHandles.constant(boolean.class, true));
        }
        return new ConstantCallSite(mh);
    }
}
